<?php

namespace app\model;

use think\facade\Log;

class DeptLeader extends BaseModel
{
    /**
     * 添加部门领导
     * @param $param
     * @return array
     */
    public function addLeader($param)
    {
        try {

            $this->insert($param);
        } catch (\Exception $e) {
            Log::error('添加部门领导错误: ' . $e->getMessage() . PHP_EOL  . $e->getTraceAsString());
            return dataReturn(-3, $e->getMessage());
        }

        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑部门领导
     * @param $param
     * @return array
     */
    public function checkAndChange($param)
    {
        try {

            if ($param['is_leader'] == 1) {

                $has = $this->where('dept_id', $param['dept_id'])->where('user_id', $param['user_id'])->find();
                if (empty($has)) {
                    $this->insert([
                        'user_id' => $param['user_id'],
                        'dept_id' => $param['dept_id']
                    ]);
                }
            } else {
                $has = $this->where('dept_id', $param['dept_id'])->where('user_id', $param['user_id'])->find();
                if (!empty($has)) {
                    $this->where('id', $has['id'])->delete();
                }
            }
        } catch (\Exception $e) {
            Log::error('编辑部门领导错误: ' . $e->getMessage() . PHP_EOL  . $e->getTraceAsString());
            return dataReturn(-3, $e->getMessage());
        }

        return dataReturn(0, '编辑成功');
    }

    /**
     * 删除部门领导
     * @param $userId
     * @return array
     */
    public function checkAndDelete($userId)
    {
        try {

            $this->where('user_id', $userId)->delete();
        } catch (\Exception $e) {
            Log::error('删除部门领导错误: ' . $e->getMessage() . PHP_EOL  . $e->getTraceAsString());
            return dataReturn(-3, $e->getMessage());
        }

        return dataReturn(0, '删除成功');
    }
}